package cn.mabach.oauth2.config;

import cn.mabach.member.entity.MemberEntity;
import cn.mabach.oauth2.project.feign.MemberServiceFeign;
import cn.mabach.oauth2.utils.UserJwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MobileUserDetailsService implements UserDetailsService {

    @Autowired
    private MemberServiceFeign memberServiceFeign;

    @Override
    public UserDetails loadUserByUsername(String mobile) throws UsernameNotFoundException {
//查询数据库
        MemberEntity memberEntity = memberServiceFeign.getByMobile(mobile).getData();
        if (memberEntity==null){
            throw new UsernameNotFoundException("手机号错误");
        }
//        封装权限
        List<String> perms = memberServiceFeign.getPermsByUsername(memberEntity.getUsername()).getData();
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        for (String perm : perms) {
            authorities.add(new SimpleGrantedAuthority(perm));
        }
        UserJwt userJwt = new UserJwt(memberEntity.getUsername(), memberEntity.getPassword(), authorities);
        userJwt.setNickname(memberEntity.getNickname());
        userJwt.setIcon(memberEntity.getQqIcon());
        return userJwt;
    }
}
